package com.zhentao.camera.controller;

import com.zhentao.camera.service.CameraService;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.Desktop;

@RestController
@RequestMapping("/api/camera")
public class CameraController {
    
    private static final Logger logger = LoggerFactory.getLogger(CameraController.class);
    
    @Autowired
    private CameraService cameraService;
    
    @PostMapping("/start/{deviceId}")
    public ResponseEntity<String> startCamera(@PathVariable("deviceId") Integer deviceId) {
        try {
            logger.debug("尝试启动摄像头，设备ID: {}", deviceId);
            if (deviceId == null) {
                deviceId = 0; // 默认使用第一个摄像头
            }
            cameraService.startCamera(deviceId);
            return ResponseEntity.ok("相机启动成功");
        } catch (Exception e) {
            logger.error("启动摄像头失败", e);
            return ResponseEntity.internalServerError().body("相机启动失败: " + e.getMessage());
        }
    }
    
    @GetMapping(value = "/frame", produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<byte[]> getFrame() {
        try {
            Frame frame = cameraService.grabFrame();
            if (frame != null) {
                Java2DFrameConverter converter = new Java2DFrameConverter();
                BufferedImage bufferedImage = converter.getBufferedImage(frame);
                if (bufferedImage != null) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "jpg", baos);
                    return ResponseEntity.ok(baos.toByteArray());
                }
            }
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("获取视频帧失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @PostMapping("/stop")
    public ResponseEntity<String> stopCamera() {
        try {
            cameraService.stopCamera();
            return ResponseEntity.ok("相机已停止");
        } catch (Exception e) {
            logger.error("停止摄像头失败", e);
            return ResponseEntity.internalServerError().body("停止相机失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/status")
    public ResponseEntity<Boolean> getCameraStatus() {
        return ResponseEntity.ok(cameraService.isRunning());
    }
    
    @PostMapping("/photo")
    public ResponseEntity<String> takePhoto() {
        try {
            String fileName = cameraService.takePhoto();
            return ResponseEntity.ok("照片已保存: " + fileName);
        } catch (Exception e) {
            logger.error("拍照失败", e);
            return ResponseEntity.internalServerError().body("拍照失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/photos/{fileName}")
    public ResponseEntity<Resource> getPhoto(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get("C:", "Users", "15134", "Desktop", "壁纸", fileName);
            Resource resource = new FileSystemResource(filePath.toFile());
            
            if (resource.exists()) {
                return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取照片失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @GetMapping("/openFolder")
    public ResponseEntity<String> openFolder(@RequestParam String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                Desktop.getDesktop().open(file.getParentFile());
                return ResponseEntity.ok("文件夹已打开");
            }
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("打开文件夹失败", e);
            return ResponseEntity.internalServerError().body("无法打开文件夹: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/photos/{fileName}")
    public ResponseEntity<String> deletePhoto(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get("C:", "Users", "15134", "Desktop", "壁纸", fileName);
            Files.deleteIfExists(filePath);
            return ResponseEntity.ok("照片已删除");
        } catch (Exception e) {
            logger.error("删除照片失败", e);
            return ResponseEntity.internalServerError().body("删除照片失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/photo/mobile")
    public ResponseEntity<String> takeMobilePhoto(@RequestParam("photo") MultipartFile photo) {
        try {
            // 生成文件名
            String fileName = "photo_" + System.currentTimeMillis() + ".jpg";
            String fullPath = "C:\\Users\\15134\\Desktop\\壁纸\\" + fileName;
            
            // 确保目录存在
            File directory = new File("C:\\Users\\15134\\Desktop\\壁纸");
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 保存文件
            File destFile = new File(fullPath);
            photo.transferTo(destFile);
            
            return ResponseEntity.ok("照片已保存: " + fileName);
        } catch (Exception e) {
            logger.error("保存手机照片失败", e);
            return ResponseEntity.internalServerError().body("保存照片失败: " + e.getMessage());
        }
    }
} 